package fr.sedoo.metadata.client.ui.widget.field.impl;

import fr.sedoo.commons.client.util.ElementUtil;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.metadata.client.message.MetadataMessage;
import fr.sedoo.metadata.client.ui.widget.field.constant.FieldConstant;
import fr.sedoo.metadata.client.ui.widget.field.primitive.ListBoxField;
import fr.sedoo.metadata.shared.domain.MetadataDTO;

public class Charset extends ListBoxField {

	private static final String charsetItems = "ucs2@ucs4@utf7@utf8@utf16@8859part1@8859part2@8859part3@8859part4@8859part5@8859part6@8859part7@8859part8@8859part9@8859part10@8859part11@8859part12@8859part13@8859part14@8859part15@8859part16@jis@shiftJIS@eucJP@usAscii@ebcdic@eucKR@big@GB2312";

	public Charset() {
		super();
		init();
	}

	/**
	 * Build the list box with the editing languages defined in the client
	 * factory
	 */
	private void init() {
		listBox.clear();
		listBox.addItem(MetadataMessage.INSTANCE.selectItem(), FieldConstant.UNSELECTED_ID);
		String[] split = charsetItems.split("@");
		for (int i = 0; i < split.length; i++) {
			listBox.addItem(split[i], split[i]);
		}

	}

	@Override
	public void display(MetadataDTO metadata) {
		ElementUtil.show(label);
		ElementUtil.hide(listBox);
		label.setText(StringUtil.trimToEmpty(metadata.getOtherPart().getCharset()));
	}

	@Override
	public void flush(MetadataDTO metadata) {
		if (listBox.getSelectedIndex() == UNSELECTED_ID_INDEX) {
			metadata.getOtherPart().setCharset("");
		} else {
			metadata.getOtherPart().setCharset(listBox.getValue(listBox.getSelectedIndex()));
		}
	}

	@Override
	public void edit(MetadataDTO metadata) {
		ElementUtil.show(listBox);
		ElementUtil.hide(label);
		String aux = StringUtil.trimToEmpty(metadata.getOtherPart().getCharset());
		if (aux.length() > 0) {
			selectByValue(aux);
		} else {
			listBox.setSelectedIndex(UNSELECTED_ID_INDEX);
		}
	}

}
